﻿using System;
using System.Web.UI;
//using COM.HS.ErrorLog;

using System.Text;
using System.Web;

using System.Runtime.InteropServices;
using System.IO;
//DOC命令引用
//using System.Text.RegularExpressions;
//using System.Diagnostics;

/// <summary>
/// 所有 aspx 页面都继承此类
/// </summary>
public class BasePage : Page
{
    #region 属性与方法

    [DllImport("Iphlpapi.dll")]
    private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length);
    [DllImport("Ws2_32.dll")]
    private static extern Int32 inet_addr(string ip);

	public string ApplicationPath;
    #endregion
	
    #region 页面载入
	protected void Page_Load(object sender, EventArgs e)
	{
		ApplicationPath = Request.ApplicationPath;
		if (ApplicationPath == "/")
		{
			ApplicationPath = "";
		}
	}
    #endregion

    #region 页面错误处理
    public void Page_Error(object sender, System.EventArgs e)
    {
    //    if (Session["USER_ID"] == null || Convert.ToString(Session["USER_ID"]) == "")
    //    {
    //        Page.RegisterStartupScript("alert", " <script language=javascript>alert('与服务器断开连接，请重新登陆！');  window.parent.location='~/Default.aspx'; </script>");
    //        return;
    //    }

        //记录错误信息到文件
        string strPaht = Server.MapPath("~/Log");
        if (!Directory.Exists(strPaht))
        {
            Directory.CreateDirectory(strPaht); 
        }
        ToTxt(Server.GetLastError(), Server.MapPath("~/Log/" + DateTime.Now.ToString("yyyy-MM-dd") + ".log"));
        string strUsername = Convert.ToString(Session["USER_NAME"]);
        string strUserid = Convert.ToString(Session["USER_ID"]);
        string strOrgcode = Convert.ToString(Session["BRANCH_ID"]);
       ToDataBase(Server.GetLastError(), strUsername, strUsername, strUserid, strOrgcode);
        Server.ClearError();

        //转到友好页面
        Response.Redirect("~/Error/Error_ErrorPage.aspx");
    }
    #endregion

    #region 用户是否登录
    public void VerdictIsLogin()
    {
        if (Session["USER_ID"] == null || Convert.ToString(Session["USER_ID"]) == "")
        {
            //转到友好页面
            StringBuilder str = new StringBuilder();
            str.Append("<script language='javascript'>\n");
            //str.Append("alert('帐号已过期，请重新登陆！');\n");
            //str.Append("top.close();\n");
            //str.Append("window.open('" + System.Web.HttpContext.Current.Request.MapPath(".").ToString() + "/Login.aspx');\n");
            //str.Append("window.open('" + GetRootURI() + "/Login/Login.aspx', \"\", \"top=150px,left=200px,height=600px,width=800px\");\n");
            str.Append("if(confirm(\"账号过期！是否重新登录？\")){\n");
            str.Append("javascript:top.location ='" + GetRootURI() + "/Login/Login.aspx'");
            str.Append("}</script>");
            Response.Write(str.ToString());
            Response.End();
        }
    }
    #endregion

    #region 获取网站虚拟目录 
    public string GetRootURI()
    {
        string AppPath = "";
        HttpContext HttpCurrent = HttpContext.Current;
        HttpRequest Req;
        if (HttpCurrent != null)
        {
            Req = HttpCurrent.Request;

            string UrlAuthority = Req.Url.GetLeftPart(UriPartial.Authority);
            if (Req.ApplicationPath == null || Req.ApplicationPath == "/")
                //直接安装在   Web   站点   
                AppPath = UrlAuthority;
            else
                //安装在虚拟子目录下   
                AppPath = UrlAuthority + Req.ApplicationPath;
        }
        return AppPath;
    }
    #endregion

    #region 获取客户端IP
    private string GetUserIP()
    {
        string _userIP;
        if (Request.ServerVariables["HTTP_VIA"] == null)
        {
            _userIP = Request.UserHostAddress;
        }
        else
        {
            _userIP = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        }
        return _userIP;
    }
    #endregion

    #region 获取客户端MAC

   

    public string GetUserMAC()
    {
        // 在此处放置用户代码以初始化页面
        try
        {
            string userip = Request.UserHostAddress;
            //string strClientIP = Request.UserHostAddress.ToString().Trim();
            string strClientIP = GetUserIP();
            Int32 ldest = inet_addr(strClientIP); //目的地的ip 
            Int32 lhost = inet_addr("");   //本地服务器的ip 
            Int64 macinfo = new Int64();
            Int32 len = 6;
            int res = SendARP(ldest, 0, ref macinfo, ref len);
            string mac_src = macinfo.ToString("X");


            while (mac_src.Length < 12)
            {
                mac_src = mac_src.Insert(0, "0");
            }

            string mac_dest = "";

            for (int i = 0; i < 11; i++)
            {
                if (0 == (i % 2))
                {
                    if (i == 10)
                    {
                        mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2));
                    }
                    else
                    {
                        mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2));
                    }
                }
            }

            return mac_dest;

            //return GetCustomerMAC(GetUserIP());
        }
        catch
        {
            return "";
        }
    }

    private string GetCustomerMAC(string strIp)
    {
        //string dirResults="";
        //ProcessStartInfo psi=new ProcessStartInfo();
        //Process proc=new Process();
        //psi.FileName="nbtstat";
        //psi.RedirectStandardInput=false;
        //psi.RedirectStandardOutput=true;
        //psi.Arguments = "-a" + strIp;
        //psi.UseShellExecute=false;
        //proc = Process.Start(psi);
        //dirResults=proc.StandardOutput.ReadToEnd();
        //proc.WaitForExit();
        //Match m=Regex.Match(dirResults,"\\w+\\-\\w+\\-\\w+\\-\\w+\\-\\w+\\-\\w\\w");
        ////返回信息
        //if(m.ToString()!="")
        //{
        //    return m.ToString();
        //}
        //else
        //{
        //    return "00:00:00:00:00";
        //}

        return "00:00:00:00:00";
    }
    #endregion

    public void SystemLoginLog(string strLoginName, string strInfo)
    {
        InsertSystemLog("Login", strInfo, strLoginName);
    }

    //操作日志
    private void InsertSystemLog(string strType, string strInfo)
    {
        //COM.HS.BLL.SYSTEM.SYSTEM_USER objBll = new COM.HS.BLL.SYSTEM.SYSTEM_USER();
        //objBll.InsertESSystemLog(GetUserIP(), GetUserMAC(), strType, strInfo, Convert.ToString(Session["USER_ID"]), Convert.ToString(Session["USER_NAME"]), Convert.ToString(Session["USER_ORGCODE"]), "", Convert.ToString(Session["USER_SYMBOL"]));
    }

    //系统管理模块的操作日志
    public void InsertSysManageLog(string strInfo)
    {
        InsertSystemLog("SysManageLog", strInfo);
    }

    //登录日志
    private void InsertSystemLog(string strType, string strInfo, string strUserSysBol)
    {
        //COM.HS.BLL.SYSTEM.SYSTEM_USER objBll = new COM.HS.BLL.SYSTEM.SYSTEM_USER();
        //objBll.InsertESSystemLog(GetUserIP(), GetUserMAC(), strType, strInfo, Convert.ToString(Session["USER_ID"]), Convert.ToString(Session["USER_NAME"]), Convert.ToString(Session["USER_ORGCODE"]), "", Convert.ToString(strUserSysBol));
    }

    //添加用户在线表信息
    public void InsertOnlineUserInfo()
    {
        //COM.HS.BLL.SYSTEM.System_OnlineUser objBll = new COM.HS.BLL.SYSTEM.System_OnlineUser();
       
        //if(objBll.GetOnlineUserInfo(Convert.ToString(Session["USER_ID"])))
        //{
        //     //用户存在，更新信息
        //    objBll.UpdateOnlineUserInfo(Convert.ToString(Session["USER_ID"]),GetUserIP());
        //}
        //else
        //{
        //    //不存在，增加信息
        //    objBll.AddOnlineUserInfo(Convert.ToString(Session["USER_ID"]), GetUserIP());
        //}

        
    }

    //记录错误日志
    public static void ToTxt(Exception exception, string path)
    {
        //整理信息内容
        StringBuilder stringBuilder = new StringBuilder(1000);
        stringBuilder.Append("============================================================================\n错误发生时间：\n   ");
        stringBuilder.Append(DateTime.Now.ToString());
        stringBuilder.Append("\n\n错误信息：\n   ");
        stringBuilder.Append(exception.ToString());
        stringBuilder.Append("\n\n\n");

        //将信息内容写入文件
      
        StreamWriter streamWriter = new StreamWriter(path, true, Encoding.Unicode);
        streamWriter.Write(stringBuilder);
        streamWriter.Close();
    }
    public static void ToDataBase(Exception exception, string strUsersymbol, string strUsername, string strUserid, string strOrgcode)
    {
        Model.SysManage.T_SYS_LOG systemLogModel = new Model.SysManage.T_SYS_LOG();
        systemLogModel.OPERATIONTIME = DateTime.Now;
        systemLogModel.USERSYMBOL = strUsersymbol;
        systemLogModel.USERNAME = strUsername;
        systemLogModel.USERID = Convert.ToInt32(strUserid);
        systemLogModel.ORGCODE = strOrgcode;
        string StrError = Convert.ToString(exception);
        if (StrError.Length > 100) //防止异常过长
        {
             StrError=StrError.Substring(0, 99);
            StrError = StrError.Replace("'", "");
        }
        systemLogModel.ERRORCONTENT = "错误信息(HS:)" + StrError;//+"错误信息："+exception.Message;
        BLL.SysManage.T_SYS_LOG logBll = new BLL.SysManage.T_SYS_LOG();
        logBll.Add(systemLogModel);
    }
}
